package com.mark.springbootdemo01.controller;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;


@RestController
@ResponseBody
@Slf4j
/**
 * 20221111-14:50 added by liuyabin
 */
public class FileController {

    @Value("${linux.imgPath}")
    private String linuxImgPath;

    @GetMapping("/testOCR")
    public String testOCR() throws TesseractException {
        String result = this.OCRHandle(new File("./test.jpg"));
        System.out.println(result);
        return result;
    }
    @PostMapping("/imgUpDown")
    public String imgUpDown(@RequestParam("file") MultipartFile file) throws IOException, TesseractException {
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换，这里使用了文件名重新生成
        fileName = UUID.randomUUID()+suffixName;

//        String path = ResourceUtils.getURL("classpath:").getPath()+ "public/img/";
        // 传到linux服务器指定路径
//        String path = "/home/mark/img/";
        file.transferTo(new File(this.linuxImgPath + fileName));

//        String filePath = "http://localhost:8081/img/"+fileName;
//        String result = this.OCRHandle(new File("./test.jpg"));
//        System.out.println(result);
        return "";
    }

    private String OCRHandle(File file) throws TesseractException {
        Tesseract tesseract = new Tesseract();
        String result = tesseract.doOCR(file);
        System.out.println(result);
        return "";
    }

//    private File convert(MultipartFile file) throws IOException {
//        File convFile = new File(file.getOriginalFilename());
//        convFile.createNewFile();
//        FileOutputStream fos = new FileOutputStream(convFile);
//        fos.write(file.getBytes());
//        fos.close();
//        return convFile;
//    }
}
